package com.example.project10;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UserRepository {
    private static final String TAG = "UserRepository";
    private static final String BASE_URL = "https://reqres.in/";
    private static final String API_KEY = "reqres-free-v1";
    private static final int TIMEOUT_SECONDS = 5; // 5秒超时
    
    private ApiService apiService;
    private Context context;
    private UserDatabaseHelper databaseHelper;
    private Handler timeoutHandler;
    private Runnable timeoutRunnable;
    private Call<UserResponse> currentCall;
    
    public UserRepository(Context context) {
        this.context = context;
        
        // 创建 OkHttpClient 并设置超时时间
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .build();
        
        // 创建 Retrofit 实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
                
        // 创建 ApiService 实例
        apiService = retrofit.create(ApiService.class);
        
        // 创建数据库帮助类实例
        databaseHelper = new UserDatabaseHelper(context);
        
        // 创建 Handler 用于处理超时
        timeoutHandler = new Handler(Looper.getMainLooper());
    }
    
    /**
     * 获取用户列表
     * @param userListLiveData 用于更新用户列表的LiveData
     * @param errorLiveData 用于更新错误状态的LiveData
     * @param loadingLiveData 用于更新加载状态的LiveData
     */
    public void fetchUsers(MutableLiveData<List<User>> userListLiveData, MutableLiveData<String> errorLiveData, MutableLiveData<Boolean> loadingLiveData) {
        // 发起网络请求
        currentCall = apiService.getUsers(API_KEY);
        
        // 设置超时处理
        timeoutRunnable = () -> {
            if (currentCall != null) {
                currentCall.cancel();
            }
            loadingLiveData.postValue(false); // 设置加载状态为false
            // 尝试从本地数据库获取数据
            loadUsersFromDatabase(userListLiveData, errorLiveData, "NETWORK_ERROR", loadingLiveData);
        };
        
        // 启动超时计时器
        timeoutHandler.postDelayed(timeoutRunnable, TIMEOUT_SECONDS * 1000);
        
        currentCall.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                // 取消超时计时器
                if (timeoutRunnable != null) {
                    timeoutHandler.removeCallbacks(timeoutRunnable);
                }
                
                loadingLiveData.postValue(false); // 设置加载状态为false
                
                if (response.isSuccessful() && response.body() != null) {
                    List<User> users = response.body().getData();
                    
                    // 按用户ID升序排序
                    if (users != null && !users.isEmpty()) {
                        Collections.sort(users, (u1, u2) -> Integer.compare(u1.getId(), u2.getId()));
                        userListLiveData.postValue(users);
                        errorLiveData.postValue(null); // 清除错误信息
                        
                        // 保存到本地数据库
                        databaseHelper.insertOrUpdateUsers(users);
                    } else {
                        // 服务器返回空数据
                        userListLiveData.postValue(new ArrayList<>());
                        errorLiveData.postValue("EMPTY_DATA");
                    }
                } else {
                    // 服务器返回错误状态码
                    Log.e(TAG, "Server error: " + response.code());
                    // 尝试从本地数据库获取数据
                    loadUsersFromDatabase(userListLiveData, errorLiveData, "SERVER_ERROR", loadingLiveData);
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {
                // 取消超时计时器
                if (timeoutRunnable != null) {
                    timeoutHandler.removeCallbacks(timeoutRunnable);
                }
                
                loadingLiveData.postValue(false); // 设置加载状态为false
                
                // 网络请求失败
                Log.e(TAG, "Network request failed", t);
                
                // 判断具体的错误类型
                String errorType = "NETWORK_ERROR";
                if (t instanceof IOException) {
                    // 网络连接问题（包括断网）
                    errorType = "NETWORK_ERROR";
                }
                
                // 尝试从本地数据库获取数据
                loadUsersFromDatabase(userListLiveData, errorLiveData, errorType, loadingLiveData);
            }
        });
    }
    
    /**
     * 从本地数据库加载用户数据
     */
    private void loadUsersFromDatabase(MutableLiveData<List<User>> userListLiveData, MutableLiveData<String> errorLiveData, String errorType, MutableLiveData<Boolean> loadingLiveData) {
        List<User> users = databaseHelper.getAllUsers();
        if (users != null && !users.isEmpty()) {
            // 本地有数据，使用本地数据
            userListLiveData.postValue(users);
            errorLiveData.postValue(null); // 清除错误信息
        } else {
            // 本地也没有数据，显示错误
            userListLiveData.postValue(new ArrayList<>());
            errorLiveData.postValue(errorType);
        }
    }
}